import sys

import facade
from bs4 import BeautifulSoup
from xjlibrary.our_file_dir import BaseDir

curPath = BaseDir.get_file_dir_absolute(__file__)
TopPath = BaseDir.get_upper_dir(curPath, -2)
sPath = BaseDir.get_new_path(TopPath, "download", "shusheng_cqjy", "download", "detail")
configfile = BaseDir.get_new_path(curPath, "db.ini")


class ParaDetail(object):

    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.mysqlutils = facade.MysqlUtiles(configfile, "db", logger=self.logger)
        self.sqlList = []

    def parse_cover(self):

        for filepath in BaseDir.get_dir_all_files(sPath):
            html = BaseDir.single_read_file(filepath, encoding='GB18030')
            soup = BeautifulSoup(html, 'lxml')
            tr_tag = soup.find("tr", valign="top")
            if tr_tag:
                imag_tag = tr_tag.find("img")
                if imag_tag:
                    url = imag_tag['src']
                    print(url)
                    bookid = BaseDir.get_filename_not_extsep(filepath)
                    if url:
                        if url == "/images/bookdefault.gif" or url == "/images/musicdefault.gif":
                            continue
                        sql = "update shusheng set cover='{}' where bookid='{}'".format(url, bookid)
                        self.sqlList.append(sql)
                        if len(self.sqlList) > 1000:
                            self.mysqlutils.ExeSqlListToDB(self.sqlList)
                            self.sqlList.clear()
                else:
                    print("没有发现这个tr标签")
                    sys.exit(-1)
            else:
                print("没有发现这个tr标签")
                sys.exit(-1)
        self.mysqlutils.ExeSqlListToDB(self.sqlList)
        self.sqlList.clear()


if __name__ == "__main__":
    para = ParaDetail()
    para.parse_cover()
